const http = require("http");
const fs = require("fs");
const path = require("path");

http.createServer((req, res) => {
    if (req.url == "/") {
        var fileContent = fs.readFileSync("./upload.html");
        res.writeHead(200, { "Content-Type": "text/html" });
        res.end(fileContent);
    } else {
        var str = "";
        req.setEncoding("binary");
        req.on("data", (chunk) => {
            str += chunk;
        });
        req.on("end", () => {
            var arr = str.split("\r\n");
            var imgarr = arr.slice(4, arr.length - 2);
            var imgstr = imgarr.join("\r\n");
            var buf = Buffer.from(imgstr, "binary");
            fs.writeFileSync(path.join(__dirname, "/img/1.png"), buf, { encoding: "binary" });
        });
    }
}).listen(8081);
console.log("server is listening on 8081");
